import os
#
from docutils.core import publish_parts

from google.appengine.api import users
from google.appengine.ext import db

from model import Language, Size, Settings

class Manager(object):
    """
    """
    def __init__(self, locale_id=None, size=None,
            language_key=None, size_key=None):
        """
        """
        # get asked language from get parameter
        if locale_id and not locale_id == '':
            self.language = self.get_language_from_id(locale_id)
        # get asked language from post
        elif language_key and not language_key == '':
            self.language = Language().get(language_key)
        else:
            self.language = self.get_default_language()

        # get asked size from get parameter
        if size and not size == '':
            self.size = self.get_size(int(size))
        # get asked size from post parameter
        elif size_key and not size_key == '':
            self.size = Size().get(size_key)
        else:
            self.size = self.get_default_size()

        query_language = Language.all()
        query_language.order('locale_id')

        query_size = Size.all()
        query_size.order('name')

        # set the template for edit
        self.template_values = {
                'admin': users.get_current_user(),
                'language': self.language,
                'languages': query_language,
                'settings': self.get_settings(),
                'size': self.size,
                'sizes': query_size}

    def get_language_from_id(self, locale_id):
        """
        """
        # get all
        query = Language().all()

        # filter the query with the expected id
        query.filter('locale_id =', locale_id)

        # no language found
        if query.count() == 0:
            #
            return self.get_default_language()

        else:
            # return the query result
            return query.get()

    def get_default_language(self):
        """
        """
        # get all
        query = Language().all()
        # filter the query looking for the current
        query.filter('default =', True)
        # no language found
        if query.count() == 0:
            # create/return the default one
            return self.__create_default_language()
        # language found
        else:
            # return the query result
            return query.get()

    def __create_default_language(self):
        """
        """
        # create a default language
        language = Language()
        # default id
        language.locale_id = db.Category('EN')
        # default name
        language.name = 'English'
        # default current false
        language.default = True
        # db update
        language.put()
        # set/return at the end (useful)
        return language

    def get_settings(self):
        """
        """
        # get all the settings
        query = Settings.all()
        query.filter('language =', self.language)

        # no settings found
        if query.count() == 0:
            # create the new settings
            settings = Settings()
            # set the language
            settings.language = self.language
            # set default values
            settings.wiki = 'Wiki'
            settings.author = 'Author'
            settings.collection = 'Collection'
            settings.picture = 'Picture'
            settings.contact = 'Contact'
            settings.start = 'from'
            settings.end = 'to'
            settings.select = 'select'
            #
            settings.put()
            # return a new settings
            return settings
        # settings found
        else:
            # return
            return query.get()

    def get_size(self, size):
        """
        """
        # get all
        query = Size().all()

        # filter the query with the expected name
        query.filter('width =', size)

        # no size found
        if query.count() == 0:
            #
            return self.get_default_size()

        else:
            # return the result
            return query.get()

    def get_default_size(self):
        """
        """
        # get all
        query = Size().all()
        # filter the query looking for the current
        query.filter('default =', True)
        # no language found
        if query.count() == 0:
            # create/return the default one
            return self.__create_default_size()
        # size fonud
        else:
            # return the query result
            return query.get()

    def __create_default_size(self):
        # create a default language
        size = Size()
        # default name
        size.name = db.Category('Classic')
        # default width
        size.width = 1024
        # default current false
        size.default = True
        # db update
        size.put()
        # return at the end (useful)
        return size

    def get_html_content(self, content):
        # get the content
        if content:
            settings = {'config' : None}
            os.environ['DOCUTILSCONFIG'] = ""
            parts = publish_parts(source=content,
                    writer_name='html4css1',
                    settings_overrides=settings)
            return parts['html_body']

        # no content
        else:
            return None

    def get_content_images(self):
        """
        """
        list_imgs = list()

        root_path = os.path.abspath('.')
        path = os.path.join(root_path, 'resources', 'img', 'content')
        for root, dirs, files in os.walk(path):
            for f in files:
                file_name = f.split('.')
                if len(file_name) == 2 \
                and (file_name[1] == 'jpg' or file_name[1] == 'JPG'):
                    img_dir = root.split('\\')[-1]
                    url = os.path.join('content', f)
                    url = url.replace('/', '-')
                    list_imgs.append(url)

        return list_imgs
